<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="到货单号" prop="arriveNumber">
        <el-input
          v-model="queryParams.arriveNumber"
          placeholder="请输入到货单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="申购单号" prop="requisitionForm">
        <el-input
          v-model="queryParams.requisitionForm"
          placeholder="请输入申购单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="产品编号" prop="productNumber">
        <el-input
          v-model="queryParams.productNumber"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="部件名称" prop="partName">
        <el-input
          v-model="queryParams.partName"
          placeholder="请输入部件名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="图纸图号" prop="drawingNumber">
        <el-input
          v-model="queryParams.drawingNumber"
          placeholder="请输入图纸图号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="业务员" prop="salesName">
        <el-input
          v-model="queryParams.salesName"
          placeholder="请输入业务员"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div style="width: 100%; height: 50px; display: flex; justify-content: space-between">
      <div>
        <el-button
          type="primary"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['outsource:outsourcing-delivery-note:export']"
        >
          数据导出
        </el-button>
      </div>
      <el-button type="primary" @click="openTableTitleSet"> 表头设置 </el-button>
    </div>
    <el-table
      ref="multipleTableRef"
      border
      :summary-method="getSummaries"
      show-summary
      row-key="id"
      :height="tableHeight"
      :tree-props="{ children: 'children' }"
      default-expand-all
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        align="center"
        :selectable="isSelected"
        :reserve-selection="true"
        type="selection"
        fixed="left"
        width="80"
      />
      <el-table-column label="序号" align="center" type="index" fixed="left" width="80" />
      <template v-for="(item, index) in tableTitleList">
        <el-table-column
          v-if="item.isTable && item.label != '序号'"
          :key="index"
          :type="item.type"
          :min-width="item.width"
          :header-align="item.headerAlign"
          :align="item.align"
          :label="item.label"
          :prop="item.field"
          :tree-props="{ children: 'children' }"
          row-key="id"
          :fixed="item.fixed"
        >
          <template #default="scope">
            <template v-if="item.field === 'action'">
              <el-button link type="primary" @click="handleDetail(scope.row)"> 查看 </el-button>
            </template>
            <template v-else>
              <dict-tag v-if="item.dictType" :type="item.dictType" :value="scope.row[item.field]" />
              <span v-else>{{ scope.row[item.field] }}</span>
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 导出 -->
  <ExportFile ref="exportRef" @download="downloadFun" />
  <!-- 表头设置 -->
  <TableWidthSet ref="tableTitleSet" @refresh="getList" />
</template>

<script setup lang="ts" name="outsourcingDeliveryNote">
  import download from '@/utils/download'
  import type { CrudSchema } from '@/hooks/web/useCrudSchemas'
  import * as outsourcingDeliveryNoteApi from '@/api/outsource/outsourceInAndOutStorage/outsourcingDeliveryNote'
  const { push } = useRouter()
  const total = ref(0) // 列表的总页数
  const list = ref<any[]>([]) // 列表的数据
  const tableTitleList = ref<CrudSchema[]>([]) // 表头列表
  const multipleTableRef = ref()
  const loading = ref(false) // 列表的加载中
  const isEdit = ref(false) //是否指派

  const queryParams = reactive({
    pageNo: 1,
    pageSize: 50,
    orderNumber: null,
    supplierName: null,
    salesName: null,
    requisitionForm: null,
    productNumber: null,
    partName: null,
    drawingNumber: null,
    arriveNumber: null,
    requirementTime: []
  })
  const queryFormRef = ref() // 搜索的表单
  const exportLoading = ref(false) // 导出的加载中
  const getSummaries = (param) => {
    const { columns, data } = param
    const sums: string[] = []
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = '总计'
        return
      }
      if (['arriveQuantity'].includes(column.property)) {
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return (parseFloat(prev) + parseFloat(curr)).toFixed(2)
            } else {
              return parseFloat(prev).toFixed(2)
            }
          }, 0)
        } else {
          sums[index] = ''
        }
      } else if (['purchaseQuantity'].includes(column.property)) {
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return (parseFloat(prev) + parseFloat(curr)).toFixed(2)
            } else {
              return parseFloat(prev).toFixed(2)
            }
          }, 0)
        } else {
          sums[index] = ''
        }
      } else if (['quantityCollected'].includes(column.property)) {
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return (parseFloat(prev) + parseFloat(curr)).toFixed(2)
            } else {
              return parseFloat(prev).toFixed(2)
            }
          }, 0)
        } else {
          sums[index] = ''
        }
      }
    })

    return sums
  }
  /**数据 */
  const getList = async () => {
    loading.value = true
    try {
      const data = await outsourcingDeliveryNoteApi.getoutsourcingDeliveryNotePage(queryParams)
      list.value = data.list
      const { allSchemas } = useCrudSchemas(data.labels)
      allSchemas.tableColumns.push({
        isTable: true,
        align: 'left',
        field: 'action',
        label: '操作',
        fixed: 'right',
        width: 80
      })
      console.log(allSchemas.tableColumns)
      tableTitleList.value = allSchemas.tableColumns
      console.log(tableTitleList.value)
      total.value = data.total
      loading.value = false
    } finally {
      loading.value = false
    }
  }
  // 多选是否启用
  const isSelected = (row) => {
    if (isEdit.value) {
      if (row.dictReportWay === 10) {
        return true
      } else {
        return row.parent !== undefined ? true : false
      }
    } else {
      return true
    }
  }

  /**选中 */
  const selectList = ref<any[]>([])
  const handleSelectionChange = (data) => {
    selectList.value = data
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.pageNo = 1
    getList()
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
  }

  /**打开表格表头设置**/
  const tableTitleSet = ref()
  const openTableTitleSet = () => {
    let code = 'outsourcingDeliveryNote'
    tableTitleSet.value.open(tableTitleList.value, code)
  }

  /** 导出按钮操作 */
  const exportRef = ref()
  const handleExport = () => {
    exportRef.value.open()
  }
  // 导出
  const downloadFun = async () => {
    const val = exportRef.value.params
    let params = {
      fileName: val.name,
      ids: ''
    }
    if (val.range === 'all') {
      params.ids = ''
    } else {
      params.ids = selectList.value.map((item) => item.id).join(',')
    }
    outsourcingDeliveryNoteApi.exportoutsourcingDeliveryNote(params).then((res) => {
      download.excel(res, val.name)
      clearSelectData()
    })
  }

  //清空多选
  const clearSelectData = () => {
    selectList.value = []
    multipleTableRef.value.clearSelection()
  }

  //查看
  const handleDetail = (data) => {
    console.log(data)
    push({
      path: '/outsource/outsource/warehousingOutbound/outsourcingDeliveryNoteForm',
      query: { list:data.arriveNumber}
    })
  }

  /** 初始化 **/
  const tableHeight = ref(0)
  onMounted(async () => {
    const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
    tableHeight.value = document.body.clientHeight - 132 - queryParamsHeight - 127
    getList()
  })
</script>
